<template>
  <div class="post-card" :class="{ 'loading': loading }" @click.stop>
    <!-- 用户信息头部 -->
    <div class="post-header">
      <div class="user-info" @click="goToUserProfile(post.author.id)">
        <div class="user-avatar">
          <img v-if="post.author.avatar || post.author.avatar_url" :src="post.author.avatar || post.author.avatar_url" :alt="post.author.username" />
          <div v-else class="default-avatar">{{ getDefaultAvatar(post.author.username) }}</div>
        </div>
        <div class="user-details">
          <h3>{{ post.author.username || '环保用户' }}</h3>
          <p class="post-meta">
            {{ formatTime(post.created_at) }}
            <span v-if="getLocationName(post.location)" class="location-tag">
              · 📍 {{ getLocationName(post.location) }}
            </span>
          </p>
        </div>
      </div>
      <button class="more-btn" @click="showMoreMenu = !showMoreMenu">⋯</button>
      
      <!-- 更多菜单 -->
      <div v-if="showMoreMenu" class="more-menu" @click.stop>
        <button v-if="isCurrentUser" @click="deletePost" class="menu-item delete">删除</button>
        <button @click="reportPost" class="menu-item report">举报</button>
      </div>
    </div>

    <!-- 动态内容 -->
    <div class="post-content">
      <p v-if="post.content" class="post-text">{{ post.content }}</p>
      
      <!-- 图片展示 -->
      <div v-if="post.images && post.images.length > 0" class="post-images">
        <div 
          v-for="(image, index) in post.images" 
          :key="index"
          class="image-item"
          :class="getImageClass(post.images.length)"
          @click="showPreviewImage(image, index)"
        >
          <img 
          :src="image" 
          :alt="`图片${index + 1}`"
          loading="lazy"
          @error="handleImageError"
          @load="handleImageLoad(index)"
          :data-index="index"
        />
          <div v-if="imageLoadingStates[index]" class="image-placeholder">
            <div class="image-loading-spinner"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 互动按钮 -->
    <div class="post-actions">
      <button 
        class="action-btn like-btn" 
        :class="{ active: post.is_liked }"
        @click="toggleLike"
      >
        <span class="leaf-icon">{{ post.is_liked ? '🍃' : '🍂' }}</span>
        <span class="count">{{ post.likes_count || 0 }}</span>
      </button>
      
      <button class="action-btn comment-btn" @click="openComments">
        <span>💬</span>
        <span class="count">{{ post.comments_count || 0 }}</span>
      </button>
      
      <button class="action-btn share-btn" @click="sharePost">
        <span>🔄</span>
        <span>分享</span>
      </button>
    </div>

    <!-- 图片预览 -->
    <div v-if="showImagePreview" class="image-preview-overlay" @click="closeImagePreview" @keydown="handlePreviewKeydown">
      <div class="preview-container" @click.stop tabindex="0">
        <button class="close-preview" @click="closeImagePreview">×</button>
        <img :src="previewImage" alt="预览图片" />
        <div class="preview-controls">
          <button @click="prevImage" :disabled="!props.post.images || currentImageIndex === 0">‹</button>
          <span>{{ currentImageIndex + 1 }} / {{ post.images?.length || 0 }}</span>
          <button @click="nextImage" :disabled="!props.post.images || currentImageIndex === (post.images.length - 1)">›</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'

interface Post {
  id: number
  author: {
    id: number
    username: string
    avatar?: string
    avatar_url?: string
  }
  content: string
  images?: string[]
  location?: string | {
    id: number
    name: string
    address?: string
  }
  created_at: string
  likes_count: number
  comments_count: number
  is_liked: boolean
}

interface Props {
  post: Post
  currentUserId?: number
}

const props = defineProps<Props>()
const emit = defineEmits<{
  like: [postId: number, isLiked: boolean]
  delete: [postId: number]
  share: [post: Post]
  comment: [postId: number]
}>()

const router = useRouter()
const showMoreMenu = ref(false)
const showImagePreview = ref(false)
const previewImage = ref('')
const currentImageIndex = ref(0)
const loading = ref(false)
const imageLoadingStates = ref<Record<number, boolean>>({})
const imageElements = ref<HTMLImageElement[]>([])

// 计算是否为当前用户的动态
const isCurrentUser = computed(() => {
  return props.currentUserId && props.post.author.id === props.currentUserId
})

// 获取默认头像
const getDefaultAvatar = (username?: string) => {
  const avatars = ['👤', '🌱', '🌿', '🍃', '🌳', '🌍', '♻️', '🚲']
  const index = username ? username.charCodeAt(0) % avatars.length : 0
  return avatars[index]
}

// 格式化时间
const formatTime = (timeStr: string) => {
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return date.toLocaleDateString('zh-CN')
}

// 获取图片样式类
const getImageClass = (count: number) => {
  if (count === 1) return 'single-image'
  if (count === 2) return 'two-images'
  if (count <= 4) return 'grid-images'
  return 'many-images'
}

// 切换点赞状态
const toggleLike = () => {
  if (loading.value) return // 防止重复点击
  
  loading.value = true
  emit('like', props.post.id, !props.post.is_liked)
  
  // 添加一个小延迟以提供视觉反馈
  setTimeout(() => {
    loading.value = false
  }, 300)
}

// 删除动态
const deletePost = () => {
  showConfirm('确定要删除这条动态吗？').then(ok => {
    if (!ok) return
    emit('delete', props.post.id)
    showMoreMenu.value = false
  })
}

// 举报动态
const reportPost = () => {
  // 这里可以实现举报逻辑
  showMessage('举报功能开发中...','success')
  showMoreMenu.value = false
}

// 分享动态
const sharePost = () => {
  emit('share', props.post)
}

// 打开评论
const openComments = () => {
  emit('comment', props.post.id)
}

// 跳转到用户主页
const goToUserProfile = (userId: number) => {
  router.push(`/profile/${userId}`)
}

// 预览图片
const showPreviewImage = (image: string, index: number) => {
  if (!image) return
  
  previewImage.value = image
  currentImageIndex.value = index
  showImagePreview.value = true
  
  // 在下一个DOM更新周期后获取焦点
  setTimeout(() => {
    const previewContainer = document.querySelector('.preview-container')
    if (previewContainer) {
      (previewContainer as HTMLElement).focus()
    }
  }, 0)
}

// 关闭图片预览
const closeImagePreview = () => {
  showImagePreview.value = false
  previewImage.value = ''
  currentImageIndex.value = 0
  // 恢复键盘焦点
  document.body.focus()
}

// 处理预览时的键盘事件
const handlePreviewKeydown = (event: KeyboardEvent) => {
  if (!props.post.images) return
  
  switch (event.key) {
    case 'ArrowLeft':
      event.preventDefault()
      prevImage()
      break
    case 'ArrowRight':
      event.preventDefault()
      nextImage()
      break
    case 'Escape':
      event.preventDefault()
      closeImagePreview()
      break
  }
}

// 上一张图片
const prevImage = () => {
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--
    previewImage.value = props.post.images?.[currentImageIndex.value] || ''
  }
}

// 下一张图片
const nextImage = () => {
  if (props.post.images && currentImageIndex.value < props.post.images.length - 1) {
    currentImageIndex.value++
    previewImage.value = props.post.images?.[currentImageIndex.value] || ''
  }
}

const showMessage = (message: string, type: 'success' | 'error' = 'success') => {
  const toast = document.createElement('div')
  toast.classList.add('message-toast')
  toast.textContent = message
  const base = 'position:fixed;left:50%;bottom:80px;transform:translateX(-50%);padding:10px 16px;border-radius:10px;color:#fff;box-shadow:0 6px 20px rgba(0,0,0,0.25);z-index:9999;font-size:14px;opacity:0.95;transition: opacity 0.3s ease;'
  const bg = type === 'success' ? 'background:#2E8B57;' : 'background:#E74C3C;'
  toast.setAttribute('style', base + bg)
  
  // 添加淡入效果
  toast.style.opacity = '0'
  document.body.appendChild(toast)
  setTimeout(() => {
    toast.style.opacity = '0.95'
  }, 10)
  
  // 设置自动移除和点击移除
  const removeToast = () => {
    toast.style.opacity = '0'
    setTimeout(() => {
      if (document.body.contains(toast)) {
        document.body.removeChild(toast)
      }
    }, 300)
  }
  
  setTimeout(removeToast, 1800)
  toast.addEventListener('click', removeToast)
}
const showConfirm = (text: string): Promise<boolean> => {
  return new Promise(resolve => {
    // 检查元素是否已存在，避免重复创建
    const existingModal = document.querySelector('.confirm-modal')
    if (existingModal) return
    
    const overlay = document.createElement('div')
    overlay.classList.add('confirm-overlay')
    overlay.setAttribute('style', 'position:fixed;inset:0;background:rgba(0,0,0,0.35);z-index:9998')
    
    const modal = document.createElement('div')
    modal.classList.add('confirm-modal')
    modal.setAttribute('style', 'position:fixed;left:50%;top:40%;transform:translate(-50%,-50%);min-width:280px;padding:18px 16px;border-radius:12px;background:#222;color:#fff;box-shadow:0 10px 30px rgba(0,0,0,0.3);z-index:9999')
    
    const msg = document.createElement('div')
    msg.textContent = text
    msg.setAttribute('style', 'font-size:14px;margin-bottom:14px')
    
    const btns = document.createElement('div')
    btns.setAttribute('style', 'display:flex;gap:10px;justify-content:flex-end')
    
    const ok = document.createElement('button')
    ok.textContent = '确定'
    ok.setAttribute('style', 'padding:6px 12px;border:none;background:#2E8B57;color:#fff;border-radius:8px;cursor:pointer')
    
    const cancel = document.createElement('button')
    cancel.textContent = '取消'
    cancel.setAttribute('style', 'padding:6px 12px;border:none;background:#555;color:#fff;border-radius:8px;cursor:pointer')
    
    ok.onclick = () => {
      modal.remove()
      overlay.remove()
      resolve(true)
    }
    
    cancel.onclick = () => {
      modal.remove()
      overlay.remove()
      resolve(false)
    }
    
    // 支持键盘Escape键取消
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        modal.remove()
        overlay.remove()
        resolve(false)
        document.removeEventListener('keydown', handleEscape)
      }
    }
    
    document.addEventListener('keydown', handleEscape)
    
    btns.appendChild(cancel)
    btns.appendChild(ok)
    modal.appendChild(msg)
    modal.appendChild(btns)
    
    document.body.appendChild(overlay)
    document.body.appendChild(modal)
  })
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  // 使用data-index属性获取索引，更可靠
  const indexAttr = img.getAttribute('data-index')
  if (!indexAttr) return
  
  const index = parseInt(indexAttr)
  imageLoadingStates.value[index] = false
  img.src = ''
}

// 处理图片加载完成
const handleImageLoad = (index: number) => {
  // 确保组件仍然挂载
  if (showImagePreview && imageLoadingStates && imageLoadingStates.value) {
    imageLoadingStates.value[index] = false
  }
}

// 初始化图片加载状态
const initializeImageLoadingStates = () => {
  // 清空现有的加载状态
  imageLoadingStates.value = {}
  
  if (props.post.images && Array.isArray(props.post.images)) {
    props.post.images.forEach((_, index) => {
      imageLoadingStates.value[index] = true
    })
  }
}

// 获取地点名称
const getLocationName = (location: any): string => {
  if (!location) return ''
  if (typeof location === 'string') return location
  return location.name || ''
}

// 组件挂载时初始化
onMounted(() => {
  initializeImageLoadingStates()
})

// 监听post变化，更新图片加载状态
watch(() => props.post.images, () => {
  initializeImageLoadingStates()
}, { deep: true })

// 点击外部关闭菜单的处理函数
const handleClickOutside = (event: Event) => {
  const target = event.target as HTMLElement
  // 检查点击目标是否是more-btn或其子元素，或者more-menu或其子元素
  const isMoreButton = target.closest('.more-btn')
  const isMoreMenu = target.closest('.more-menu')
  
  if (!isMoreButton && !isMoreMenu) {
    showMoreMenu.value = false
  }
}

// 添加点击事件监听器
document.addEventListener('click', handleClickOutside)

// 组件卸载时移除事件监听器，避免内存泄漏
import { onUnmounted } from 'vue'
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.post-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  position: relative;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  gap: 12px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-avatar {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #42b983, #2c8a65);
  color: white;
  font-size: 18px;
}

.user-details h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
}

.user-details p {
  margin: 2px 0 0 0;
  font-size: 12px;
  color: #7f8c8d;
}

.location-tag {
  color: #1677ff;
  font-weight: 500;
  cursor: pointer;
  transition: opacity 0.2s;
}

.location-tag:hover {
  opacity: 0.8;
}

.more-btn {
  background: none;
  border: none;
  font-size: 18px;
  color: #adb5bd;
  cursor: pointer;
  padding: 5px;
  border-radius: 50%;
  transition: all 0.2s;
}

.more-btn:hover {
  background: #f8f9fa;
  color: #495057;
}

.more-menu {
  position: absolute;
  top: 50px;
  right: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  z-index: 10;
  overflow: hidden;
}

.menu-item {
  display: block;
  width: 100%;
  padding: 10px 15px;
  border: none;
  background: white;
  text-align: left;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.menu-item:hover {
  background: #f8f9fa;
}

.menu-item.delete {
  color: #dc3545;
}

.menu-item.report {
  color: #ffc107;
}

.post-content {
  padding: 0 15px 15px;
}

.post-text {
  margin: 0 0 15px 0;
  line-height: 1.5;
  color: #2c3e50;
  font-size: 14px;
}

.post-images {
  display: grid;
  gap: 4px;
  border-radius: 8px;
  overflow: hidden;
}

.image-item {
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s;
}

.image-item:hover {
  transform: scale(1.02);
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.image-item:hover img {
  transform: scale(1.05);
}

.image-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f0f0;
}

.image-loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #42b983;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.post-card.loading {
  opacity: 0.7;
}

.single-image {
  grid-template-columns: 1fr;
  max-height: 300px;
}

.two-images {
  grid-template-columns: 1fr 1fr;
  aspect-ratio: 16/9;
}

.grid-images {
  grid-template-columns: repeat(2, 1fr);
  aspect-ratio: 1;
}

.many-images {
  grid-template-columns: repeat(3, 1fr);
  aspect-ratio: 1;
}

.post-actions {
  display: flex;
  padding: 12px 15px;
  border-top: 1px solid #f0f0f0;
  gap: 20px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 14px;
  padding: 8px 12px;
  border-radius: 20px;
  transition: all 0.2s;
  flex: 1;
  justify-content: center;
}

.action-btn:hover {
  background: #f8f9fa;
  color: #42b983;
}

.action-btn.like-btn.active {
  color: #42b983;
  background: rgba(66, 185, 131, 0.1);
}

.leaf-icon {
  font-size: 16px;
}

.count {
  font-weight: 500;
}

.image-preview-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.preview-container {
  position: relative;
  max-width: 90vw;
  max-height: 90vh;
}

.preview-container img {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
}

.close-preview {
  position: absolute;
  top: -40px;
  right: 0;
  background: none;
  border: none;
  color: white;
  font-size: 30px;
  cursor: pointer;
  padding: 5px;
}

.preview-controls {
  position: absolute;
  bottom: -40px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 20px;
  color: white;
}

.preview-controls button {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  font-size: 20px;
  padding: 10px;
  border-radius: 50%;
  cursor: pointer;
  transition: background 0.2s;
}

.preview-controls button:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.3);
}

.preview-controls button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
